//
//  HMEmoticonPageCell.swift
//  Weibo02
//
//  Created by teacher on 16/4/28.
//  Copyright © 2016年 teacher. All rights reserved.
//

import UIKit

class HMEmoticonPageCell: UICollectionViewCell {
    
    /// 供外界设置数组的属性
    var emoticons: [HMEmoticon]? {
        didSet{
            
            // 让表情按钮显示数据
            guard let e = emoticons else {
                return
            }
            
            // 先隐藏所有的按钮 （因为涉及到复用，所以我们需要设置一个表情就显示一个表情）
            for value in emoticonButtons {
                value.hidden = true
            }
            
            
            // 遍历表情数组，设置表情数据
            for (index,emoticon) in e.enumerate() {
                let button = emoticonButtons[index]
                button.hidden = false
                
                button.emoticon = emoticon
//                // 判断是 emoji 表情还是图片表情
//                if emoticon.type == "1" {
//                    // 是 emoji 表情
//                    button.setTitle((emoticon.code! as NSString).emoji(), forState: UIControlState.Normal)
//                    // 因为会复用，所以设置emoji表情的时候，需要将图片给干掉
//                    button.setImage(nil, forState: UIControlState.Normal)
//                }else{
//                    // 设置图片表情数据
//                    let image = UIImage(named: "\(emoticon.folderName ?? "")/\(emoticon.png ?? "")", inBundle: HMEmoticonKeyBoardViewModel.sharedViewModel.emoticonBundle, compatibleWithTraitCollection: nil)
//                    button.setImage(image, forState: UIControlState.Normal)
//                    button.setTitle(nil, forState: UIControlState.Normal)
//                }
            }
        }
    }
    private lazy var emoticonButtons: [HMEmoticonButton] = []
    
    // 为了测试，显示当前cell是第几组第几个item
    var indexPath: NSIndexPath? {
        didSet{
            messageLabel.hidden = indexPath?.section != 0
//            label.text = "第\(indexPath?.section ?? 0)组，第\(indexPath?.item ?? 0)页"
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
//        backgroundColor = RandomColor
        
        
        contentView.addSubview(messageLabel)
        
        messageLabel.snp_makeConstraints { (make) -> Void in
            make.centerX.equalTo(contentView)
            make.bottom.equalTo(contentView).offset(-10)
        }
        addChildButtons()
        contentView.addSubview(deleteButton)
        
        // 给contentView添加长按的手势
        let longPress = UILongPressGestureRecognizer(target: self, action: "longPress:")
        // 最短的触发时间
//        longPress.minimumPressDuration = 5
        contentView.addGestureRecognizer(longPress)
        
    }
    
    // 添加20个表情按钮
    private func addChildButtons(){
        
        let maxCount = HMEmoticonKetboardPageEmticonCount
        
        for _ in 0..<maxCount {
            let button = HMEmoticonButton()
            // 添加点击事件
            button.addTarget(self, action: "emoticonButtonClick:", forControlEvents: UIControlEvents.TouchUpInside)
            button.titleLabel?.font = UIFont.systemFontOfSize(35)
//            button.backgroundColor = RandomColor
            // 添加到当前的contentView里面
            contentView.addSubview(button)
            // 添加到按钮数组里面作记录，以便在layoutSubviews里面可以直接取到按钮
            emoticonButtons.append(button)
        }
        
    }
    
    
    // MARK: - 监听事件
    
    
    /// 长按显示popView事件
    ///
    /// - parameter ges: <#ges description#>
    @objc private func longPress(ges: UILongPressGestureRecognizer){
        
        
        // 1. 取到手指所在的位置
        let location = ges.locationInView(ges.view)
        
        print(location)
        
        // 2. 找到该位置所对应的按钮
        func buttonWithLocation(location: CGPoint) -> HMEmoticonButton? {
            for value in emoticonButtons {
                //if value的范围是否包含传入的点，如果包含，直接返回value
                if CGRectContainsPoint(value.frame, location) {
                    return value
                }
            }
            return nil
        }
        
        // 通过点找到点对应的表情按钮
        guard let button = buttonWithLocation(location) else {
            popView.removeFromSuperview()
            return
        }
        
        switch ges.state {
        case .Began,.Changed:
            if popView.emoticonButton.emoticon == button.emoticon {
                return
            }
            // 0. 取到最上层的window
            let window = UIApplication.sharedApplication().windows.last!
            // 2.1 坐标转换：将按钮在contentView里面的坐标值转换到window上面
            // converRect： __.convertRect(__, toView: __)
            let rect = button.superview!.convertRect(button.frame, toView: window)
            // 中心点一样
            popView.center.x = CGRectGetMidX(rect)
            popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
            // 给 PopView里面的按钮赋值
            popView.emoticonButton.emoticon = button.emoticon
            // 3. 添加
            window.addSubview(popView)
        default:
            popView.emoticonButton.emoticon = nil
            popView.removeFromSuperview()
        }
        
//        // 3. 显示popView
//        let popView = HMEmoticonPopView.popView()
    }
    
    @objc private func deleteButtonClick(){
        
        // 通知控制器让textView去回删一个
        NSNotificationCenter.defaultCenter().postNotificationName(HMEmoticonDeleteButtonClickNotification, object: nil)
    }
    
    /// 表情按钮点击的事件
    ///
    /// - parameter button: <#button description#>
    @objc private func emoticonButtonClick(button: HMEmoticonButton) {
        
        // 发送一个通知
        NSNotificationCenter.defaultCenter().postNotificationName(HMEmoticonButtonClickNotification, object: nil, userInfo: ["emoticon": button.emoticon!])
        
        // 0. 取到最上层的window
        let window = UIApplication.sharedApplication().windows.last!
        
        // 1. 初始化一个popView
        let popView = HMEmoticonPopView.popView()
        // 2. 设置当前popView的位置
        
        // 2.1 坐标转换：将按钮在contentView里面的坐标值转换到window上面
        // converRect： __.convertRect(__, toView: __)
        let rect = button.superview!.convertRect(button.frame, toView: window)
        
        // 中心点一样
        popView.center.x = CGRectGetMidX(rect)
        popView.frame.origin.y = CGRectGetMaxY(rect) - popView.frame.height
        // 给 PopView里面的按钮赋值
        popView.emoticonButton.emoticon = button.emoticon
        // 3. 添加
        window.addSubview(popView)
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double(NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            popView.removeFromSuperview()
        }
        
    }
    
    /// 计算表情按钮的大小与位置
    override func layoutSubviews() {
        super.layoutSubviews()
        
        
        // 每一个按钮的宽度
        let itemW = self.frame.width / CGFloat(HMEmoticonKetboardMaxCol)
        // 每一个按钮的高度
        let itemH = (self.frame.height - 25) / CGFloat(HMEmoticonKetboardMaxRow)
        // 调整20个按钮的大小与位置.取到20个
        for (index,value) in emoticonButtons.enumerate() {
            
            // 确定在第几列
            let col = index % HMEmoticonKetboardMaxCol
            // 确定在第几行
            let row = index / HMEmoticonKetboardMaxCol
            // 设置位置
            let x = CGFloat(col) * itemW
            let y = CGFloat(row) * itemH
            // 设置大小
            value.frame = CGRect(x: x, y: y, width: itemW, height: itemH)
        }
        
        
        // 设置删除按钮的位置
        let deleteButtonX = self.frame.width - itemW
        let deleteButtonY = self.frame.height - itemH - 25
        
        deleteButton.frame = CGRect(x: deleteButtonX, y: deleteButtonY, width: itemW, height: itemH)
    }
    
    /// 删除按钮
    private lazy var deleteButton: UIButton = {
        let button = UIButton()
        // 添加点击事件
        button.addTarget(self, action: "deleteButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        button.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
        button.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
        
        return button
    }()
    
    
    // 消息label
    private lazy var messageLabel: UILabel = {
        let label = UILabel(textColor: UIColor.grayColor(), fontSize: 12)
        label.text = "最近使用的表情"
        return label
    }()
    
    
    /// 长按出现的popView
    private lazy var popView: HMEmoticonPopView = {
        let popView = HMEmoticonPopView.popView()
        return popView
    }()
}
